package com.xunji.user.config;


import com.xunji.user.common.Constant;
import com.xunji.user.common.Token;
import com.xunji.user.common.TokenUtils;
import com.xunji.user.service.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 配置请求拦截器
 *
 * @Author qiangxu9
 * @Date 2021年07月15日 星期四
 * @Version 1.0
 * @Description trial-service
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Value("${trial.token.enable:false}")
    private boolean trialTokenEnable;
    @Value("${web_expire_date:7}")
    private long webExpireDate;

    @Resource
    private CacheService cacheService;

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {

        String token = request.getHeader("Authorization");
        String from = "0";
        if (!trialTokenEnable) { // 不开启拦截器
            return true;
        }

        if (token != null) {
            // token校验通过之后,再校验token的合法性
            String uuidUserName = Token.getInstance().getUsername(token);

            String userId = TokenUtils.getUserId(token);
            if (StringUtils.isEmpty(userId)) {
                log.error("非法token，被拦截,返回302状态码! requestUri=[}", request.getRequestURI());
                response.sendError(302);
                return false;
            }
            String cacheKey = TokenUtils.genSessionKey(userId, from);

            String cacheUuidUserName = cacheService.get(cacheKey, String.class);
            if (StringUtils.isEmpty(cacheUuidUserName)) {
                log.error("token过期，被拦截,返回302状态码! requestUri=[}", request.getRequestURI());
                response.sendError(302);
                return false;
            }
            if (!uuidUserName.equals(cacheUuidUserName)) {
                log.error("token过期,已被更新，被拦截,返回302状态码! requestUri=[}", request.getRequestURI());
                response.sendError(302);
                return false;
            }
            long newExpireTime;
            // 时间戳小于配置的客户端过期时间
            newExpireTime = webExpireDate * Constant.ONE_DAY;
            cacheService.set(cacheKey, cacheUuidUserName, newExpireTime);
            return true;
        }
        log.info("token为空,被拦截,返回302状态码! {}", request.getRequestURI());
        response.sendError(302); // 校验不通过,自定义返回状态码
        return false;
    }
}
